import axios from 'axios'
// import qs from 'qs'
import { ElMessage } from 'element-plus'

window.axiosCancel = []
axios.defaults.timeout = 100000
axios.defaults.headers.post['Content-Type'] = 'application/x-wwsw-form-urlencoded;charset=UTF-8'

axios.interceptors.request.use(
  function (config) {
    let token = ''
    config.headers = {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Http-Api-Token': token
    }

    config.cancelToken = new axios.CancelToken((cancel) => {
      window.axiosCancel.push({
        cancel
      })
    })
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)
axios.interceptors.response.use(
  (response) => {
    if (response.data.code === 200) {
      return Promise.resolve(response)
    } else if (response.data.code === 601) {
      // window.location.href = "/login";
    } else {
      // console.log(response);
      return Promise.reject(response)
    }
  },
  (error) => {
    console.log(error.response.code)
    if (error.response.code) {
        switch(err.response.status){
            case 401:
                switch(err.response.data.error){
                    case 'Identity is overdue':
                        ElMessage.error('身份过期请重新登录');
                        break;
                    case '用户不存在':
                        ElMessage.error('该用户未注册，请到注册页进行注册!');
                        break;
                    case 'no login':
                        ElMessage.error('未登录');
                        break;
                }
                localStorage.removeItem('token');
                break;
            case 500:
                ElMessage.error("服务器故障");
                break
            case 422:
                break;
            default:
                ElMessage.error("服务器故障!")
                break;
        }
      return Promise.reject(error.response)
    }
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params
      })
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res.data)
      })
      .catch((err) => {
        reject(err.data)
      })
  })
}
